package id.co.shuba.spamobile.activities;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.ISharedDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.list.PipelineListFragment;
import id.co.shuba.spamobile.list.PipelineListFragment.OnPipelineSelectedListener;
import id.co.shuba.spamobile.util.StyleUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class PipelineListActivity extends SherlockFragmentActivity implements
		ISharedDB, ActionBar.OnNavigationListener, ActionMode.Callback,
		OnPipelineSelectedListener, OnItemLongClickListener {
		
	private DatabaseHandler _db;
	private ProspectDB _prospectDB;
	
	private PipelineListFragment _list;	
	private String _prospectID;	

	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_pipeline, menu);

		MenuItem item = menu.findItem(R.id.menu_search);
		final EditText searchText = (EditText) item.getActionView();

		FragmentManager fm = getSupportFragmentManager();
		_list = (PipelineListFragment) fm.findFragmentById(R.id.lstFragment);
		_list.setAoCode(Sessions.getUser(this).getAoCode());
		_list.setOnPipelineSelectedListener(this);
		_list.getListView().setOnItemLongClickListener(this);

		TextWatcher textWatcher = new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				_list.setFilter(s.toString());
				_list.reload();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
			}
		};
		searchText.addTextChangedListener(textWatcher);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add:
			add();
			return true;
		case R.id.menu_sort:
			sort();
			return true;					
		case R.id.menu_refresh:
			_list.reload();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pipeline);
		setUpLogoutReceiver();
		
		_db = new DatabaseHandler(this);
		_prospectDB = new ProspectDB(_db);
		
		StyleUtil.applyStyle(this);
		
		//_pipelineDB.makeAllInbox();	

		Context context = getSupportActionBar().getThemedContext();
		ArrayAdapter<CharSequence> list = ArrayAdapter
				.createFromResource(context, R.array.pipeline_entry,
						R.layout.sherlock_spinner_item);
		
		list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

		boolean inbox = getIntent().getBooleanExtra("INBOX", false);
		ActionBar bar = getSupportActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		bar.setListNavigationCallbacks(list, this);			
		
		if (inbox)
			bar.setSelectedNavigationItem(2);
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {		
		_list.setType(itemPosition);
		_list.reload();
		return true;
	}

	@Override
	public boolean onCreateActionMode(ActionMode mode, Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_pipeline_view, menu);		
		
		return true;
	}

	@Override
	public boolean onPrepareActionMode(ActionMode mode, Menu menu) {		
		return false;
	}

	@Override
	public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_edit:
			edit();
			break;
		case R.id.menu_delete:
			delete();
			break;
		case R.id.menu_data_pelengkap:
			detail();		
			break;								
		}
		mode.finish();
		return true;
	}

	private void delete() {
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.delete)
        .setMessage(R.string.delete_confirm)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	dialog.dismiss();
                _prospectDB.delete(_prospectID, Sessions.getUser(PipelineListActivity.this).getNip());
                _list.reload();                       
            }
        })        
        .setNegativeButton(R.string.no, null)
        .show(); 
	}

	@Override
	public void onDestroyActionMode(ActionMode mode) {
	}

	@Override
	public DatabaseHandler getDB() {
		return _db;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK
				&& (requestCode == App.REQUEST_EDIT_PIPELINE || requestCode == App.REQUEST_VIEW_PROSPECT)) {
			_list.reload();
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();
	}

	@Override
	public void onPipelineSelected(String id) {
		Intent intent = new Intent(PipelineListActivity.this,
				PipelineViewActivity.class);
		intent.putExtra("prospectID", id);
		startActivityForResult(intent, App.REQUEST_VIEW_PROSPECT);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		//_prospectID = parent.getItemAtPosition(position);
		//startActionMode(this);
		return true;
	}
	
	private void add() {
		Intent intent = new Intent(this, FormPipelineActivity.class);
		startActivityForResult(intent, App.REQUEST_EDIT_PIPELINE);
	}

	private void edit() {
		Intent intent = new Intent(this, FormPipelineActivity.class);
		intent.putExtra("prospectID", _prospectID);

		startActivityForResult(intent, App.REQUEST_EDIT_PIPELINE);
	}

	private void detail() {
		Intent intent = new Intent(this, FormProspectActivity.class);
		intent.putExtra("prospectID", _prospectID);

		startActivityForResult(intent, App.REQUEST_VIEW_PROSPECT);
	}
	
	private void sort() {
		String optionFullName = getString(R.string.full_name);
		String optionPlafonPlan = getString(R.string.plafon_plan);
		String optionPrn = getString(R.string.prn_number);
		
		final CharSequence[] items = new CharSequence[] { optionFullName, optionPlafonPlan, optionPrn };						
		
		AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog));
		builder.setTitle("Sort By");
		builder.setItems(items, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {		
		    	String sort = "PROSPECT_NO";
		    	if (item == 0) {
		    		sort = "FULL_NAME";
		    	} else if (item == 1) {
		    		sort = "RENCANA_PLAFON";
		    	}		    	
		    	_list.setSort(sort);
		    	_list.reload();
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}	
}
